package cn.lix.sc.rpc.impl.common.exception;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 异常父类
 * @date 2021/4/27
 * @author lix
 * @email sclx1220@163.com
 */
public abstract class BaseException extends RuntimeException {

    public static final String REGX_PLACEHOLDER = "\\{\\}";

    /**
     * 匹配正则占位符{}
     */
    private static final Pattern SIGN = Pattern.compile(REGX_PLACEHOLDER);
    /**
     * 错误代码
     */
    private Integer code;
    /**
     * 错误描述
     */
    private String desc;
    /**
     * 补位参数
     */
    private transient Object[] args;
    /**
     * 异常对象
     */
    private transient Throwable throwable;


    protected BaseException(Throwable cause, Integer code, String desc, Object... args) {
        super(formatMessage(desc, args), cause);
        this.desc = desc;
        this.args = args;
        this.code = code;
    }

    public static String formatMessage(String message, Object[] args) {
        if (message == null || message.length() < 1) return "unknown exception";
        if (args == null || args.length < 1) {
            return message.contains("{}") ? message.replaceAll(REGX_PLACEHOLDER, "") : message;
        }
        try {
            Matcher matcher = SIGN.matcher(message);
            StringBuffer stringBuffer = new StringBuffer(64);
            int i = 0;
            while (matcher.find()) {
                matcher.appendReplacement(stringBuffer, String.valueOf(args[i++]));
            }
            matcher.appendTail(stringBuffer);
            return stringBuffer.toString();
        } catch (Exception ex) {
            return message + ",errorArgs:" + args;
        }
    }

    public Integer getCode() {
        return code;
    }

    public Object[] getArgs() {
        return args;
    }

    public Throwable getThrowable() {
        return throwable;
    }

    public String getDesc() {
        return desc;
    }


}
